package com.spring.use.jms.txlistener;

import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

/**
 * 生产者端创建事务消息监听器（执行本地事务的监听器）
 */
@RocketMQTransactionListener
@Component
public class TxMessageListener implements RocketMQLocalTransactionListener {

    // 执行本地事务
    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message msg, Object arg) {
        System.out.println("执行本地事务...");
        RocketMQLocalTransactionState state = RocketMQLocalTransactionState.ROLLBACK;

        try {
            // .....逻辑处理
            //int a = 1 / 0;
            Thread.sleep(60*1000);// 进入检查本地事务结果方法
            // 执行本地事务
            state = RocketMQLocalTransactionState.COMMIT;
        }catch (Exception e){
            // 消息回滚
            state = RocketMQLocalTransactionState.UNKNOWN;
        }
        System.out.println("executeLocalTransaction 执行本地事务 return "+state);
        return state;
    }

    // 检查本地事务结果方法（上面执行本地事务方法一直没有返回状态的时候，会进入这个方法）
    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message msg) {
        System.out.println("执行检查本地事务...");
        // 检查本地事务
        RocketMQLocalTransactionState state = RocketMQLocalTransactionState.COMMIT;
        try {
            // ... 执行逻辑  与 上面逻辑差不多
        }catch (Exception e){
            // 异常就回滚
            state = RocketMQLocalTransactionState.ROLLBACK;
        }
        return state;
    }
}
